package com.dlc.felear.xiaoensale.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.activity.SelectperatorActivity;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.dao.ActionStepItemDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.deviceControlSf.OperatorAutoHandle;
import com.dlc.felear.xiaoensale.entity.ActionStepItem;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.Session;
import com.itdlc.android.library.listener.TextWatcherAdapter;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


public class OperatorItemAdapter extends BaseAdapter implements View.OnClickListener {

    private static final String TAG = "OperatorItemAdapter";
    // 上下文
    private Context context;
    private AppCompatActivity activity;
    // 数据
    private List<Operator> items;
    private int index = 0;
    private boolean enableDelete = true;
    private ActionStepItemDao actionStepItemDao;
    private OperatorDao operatorDao;
    private OperatorAutoHandle operatorAutoHandle;
    private HashMap<String, Integer> recordData = new HashMap<>();
    private HashMap<String, Object> paramer1;
    private int cookingType = 1;
    private String type = "M400";
    private int geziDelay = 20;
    private String src = "src1";


    public void setCcCookingTimeParamer(String paramer1) {
        try {
            Log.e(TAG, "参数信息:" + paramer1);
            if (!TextUtils.isEmpty(paramer1)) {
                this.paramer1 = JsonHelper.parserJson(StringEscapeUtils.unescapeJava(paramer1), HashMap.class);
            }
        } catch (Exception e) {
            this.paramer1 = null;
        }
    }

    public void setCookingType(int cookingType) {
        Log.e(TAG, "烹饪方式:" + cookingType);
        this.cookingType = cookingType;
    }

    public void setEnableDelete(boolean flag) {
        enableDelete = flag;
    }

    public OperatorItemAdapter(Context context, String src) {
        this.context = context;
        this.src = src;
        this.activity = (AppCompatActivity) context;
        items = new ArrayList<>();
        operatorDao = new OperatorDao(context);
        actionStepItemDao = new ActionStepItemDao(context);
        operatorAutoHandle = OperatorAutoHandle.getInstance(null, null, TAG);
        type = Session.getSession().getString(Constant.D_GT_TYPE, "M260");
        if (TextUtils.equals(type, "M600")) {
            geziDelay = 25;
        }
    }

    public List<Operator> getData() {
        return items;
    }

    public void setItems(List<Operator> data) {
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void setItems(List<Operator> data, float size, boolean resetCc) {
        try {
            Collections.sort(data);
            List<Operator> tempList = new ArrayList<>();
            for (Operator operator : data) {
                Log.e(TAG, "operator1=" + JsonHelper.toJson(operator));
                if (TextUtils.equals(operator.getName(), "请选择")) {
                    continue;
                }
                ActionStepItem temp = actionStepItemDao.queryForAllByName(operator.getName());
                if (temp != null) {
                    operator.setSerial(temp.getSerialNo());
                } else {
                    continue;
                }
                if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_JSC)) {
                    if (operator.getDelayTime() == 1) {
                        operator.setDelayTime(1);
                    } else {
                        operator.setDelayTime(geziDelay);
                    }
                }
                if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_CCSC)) {
                    if (!recordData.containsKey(operator.getName())) {
                        recordData.put(operator.getName(), operator.getValue1());
                    }
                    float y = operatorAutoHandle.getCcDealay(paramer1, size, cookingType, operator.getValue1());
                    operator.setDelayTime((int) Math.ceil(y));
                }
                if (temp.getType() == Constant.ACTION_STEP_JGT
                        || temp.getType() == Constant.ACTION_STEP_JYT) {
                    if (!recordData.containsKey(operator.getName() + "_" + operator.getNum())) {
                        recordData.put(operator.getName(), operator.getValue1());
                    }
                    operator.setValue1((int) (size * recordData.get(operator.getName())));
                    operator.setDelayTime(getdelayTlTime(operator, operator.getValue1()));
                }
                if (operator.getDelayTime() <= 0) {
                    operator.setDelayTime(1);
                }
                tempList.add(operator);
            }
            Log.e(TAG, "operator3=" + JsonHelper.toJson(tempList));
            items.clear();
            if (resetCc) {
                items.addAll(clcCTime(tempList, size, resetCc));
            } else {
                items.addAll(tempList);
            }
            notifyDataSetChanged();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * 通过公式计算炒菜时间
     *
     * @param tempList
     * @param size
     * @param resetCc
     * @return
     */
    private List<Operator> clcCTime(List<Operator> tempList, float size, boolean resetCc) {
        if (index <= 0 || index >= tempList.size()) {
            return tempList;
        }
        try {
            for (int i = 0; i < tempList.size(); i++) {
                Operator operator = tempList.get(i);
                if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_CCSC)) {
                    tempList.remove(i);
                    if (resetCc && paramer1 != null) {
                        operator.setDelayTime(operatorAutoHandle.getCcDealay(paramer1, size, cookingType, operator.getValue1()));
                    }
                    tempList.add(i, operator);
                    break;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "clcCTime Exception:" + e.getMessage());
        }
        return tempList;
    }

    public void resetAllParamer(float size) {
        try {
            List<Operator> tempList = new ArrayList<>();
            tempList.addAll(items);
            setItems(tempList, size, true);
//            for (int i = 0; i < items.size(); i++) {
//                Operator operator = items.get(i);
//                if () {
//                    float y = operatorAutoHandle.getCcDealay(paramer1, size, cookingType, operator.getValue1());
////                    operator.setValue(operatorAutoHandle.getCcDealay(paramer1, size, cookingType));
//                    operator.setDelayTime((int) y);
//                    tempList.add(i, operator);
//                }else if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_CCSC) && paramer1 != null) {
//                    float y = operatorAutoHandle.getCcDealay(paramer1, size, cookingType, operator.getValue1());
////                    operator.setValue(operatorAutoHandle.getCcDealay(paramer1, size, cookingType));
//                    operator.setDelayTime((int) y);
//                    tempList.add(i, operator);
//                } else if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_SHUI) && cookingType == 2 && paramer1 != null) {
//                    //y=f*[a(x-b)+c)]+C
//                    float value = getFloatMapValue(paramer1, "f") * operatorAutoHandle.getCcDealay(paramer1, size, cookingType) + operator.getValue();
//                    operator.setValue1((int) Math.ceil(value));
//                    operator.setDelayTime(operator.getValue1());
//                    tempList.add(i, operator);
//                } else {
//                    tempList.add(i, operator);
//                }
//            }
//            items.clear();
//            items.addAll(tempList);
//            notifyDataSetChanged();
        } catch (Exception e) {
            Log.e(TAG, "clcCTime Exception:" + e.getMessage());
        }
    }


    public Operator getStdOperator(Operator operator, float weight) {
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_CCSC)) {
            if (paramer1 != null) {
                float y = operatorAutoHandle.getCcDealay(paramer1, weight, cookingType, operator.getValue1());
//                operator.setValue(operatorAutoHandle.getCcDealay(paramer1, weight, cookingType));
                operator.setDelayTime((int) y);
            }
        } else if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_SHUI) && cookingType == 2) {
            if (paramer1 != null) {
                //y=f*[a(x-b)+c)]+C
                float value = getFloatMapValue(paramer1, "f") * operatorAutoHandle.getCcDealay(paramer1, weight, cookingType) + operator.getValue();
                operator.setValue1((int) Math.ceil(value));
                operator.setDelayTime(operator.getValue1());
            }
        }
        return operator;
    }


    private float getFloatMapValue(HashMap<String, Object> hashMap, String key) {
        float temp = -1;
        if (hashMap.containsKey(key)) {
            temp = Float.parseFloat(hashMap.get(key).toString());
            Log.e(TAG, "key=" + key + " value=" + hashMap.get(key) + "temp=" + temp);
        }
        return temp;
    }


    public void initFirstOperator() {
        items.clear();
        items.add(new Operator(1));
        notifyDataSetChanged();
    }

    public void updateData(String name, int value, int value2, float size) {
        Log.e(TAG, "name=" + name + " value1=" + value + " value2=" + value2);
        ActionStepItem temp = actionStepItemDao.queryForAllByName(name);
        Operator operator = items.get(index);
        if (temp != null) {
            operator.setSerial(temp.getSerialNo());
        }
        operator.setName(name);
        operator.setValue(value);
        operator.setValue1(value2);
        operator.setDelayTime(1);
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_KSJB)) {
            operator.setValue1(value);
            operator.setValue(value2);
        }
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_CCJD) ||
                TextUtils.equals(operator.getName(), Constant.ACTION_NAME_JC)) {
            operator.setDelayTime(value);
        }
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_CCSC)) {
            operator.setValue1(value2);
            int y = operatorAutoHandle.getCcDealay(paramer1, size, cookingType, value2);
            Log.e(TAG, "炒菜时长换算:" + y + " paramer1:" + JsonHelper.toJson(paramer1) + " size=" + size + " cookingType=" + cookingType + " 系数:" + value2);
            operator.setDelayTime((int) y);
        }
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_JC)) {
            operator.setDelayTime(value2);
        }
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_JSC)) {
            operator.setDelayTime(20);
        }
        if (temp.getType() == Constant.ACTION_STEP_JGT || temp.getType() == Constant.ACTION_STEP_JYT) {
            operator.setDelayTime(getdelayTlTime(operator, value2));
            if (!recordData.containsKey(operator.getName() + "_" + operator.getNum())) {
                recordData.put(operator.getName(), operator.getValue1());
            }
        }
        items.remove(index);
        items.add(index, operator);
        notifyDataSetChanged();
    }

    private int getdelayTlTime(Operator operator, int value) {
        if (TextUtils.equals(Constant.ACTION_NAME_YOU, operator.getName())) {
            return 1;
        }
        return operatorAutoHandle.mlVavluechangeMsec(operator.getName(), value) / 1000;
    }

    public void clearData() {
        items.clear();
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Operator getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        holder = new ViewHolder();
        convertView = View.inflate(context, R.layout.adapter_operator_item, null);
        holder.o_tv_num = convertView.findViewById(R.id.o_tv_num);
        holder.o_tv_select = convertView.findViewById(R.id.o_tv_operator);
        holder.et_time = convertView.findViewById(R.id.o_et_time);
        holder.iv_delete = convertView.findViewById(R.id.o_iv_delete);
        holder.iv_add = convertView.findViewById(R.id.o_iv_add);
        holder.iv_minus = convertView.findViewById(R.id.o_iv_minus);
        holder.iv_step = convertView.findViewById(R.id.o_iv_step);
        holder.iv_step.setTag(position);
        holder.o_tv_select.setTag(position);
        holder.iv_delete.setTag(position);
        holder.iv_add.setTag(position);
        holder.iv_minus.setTag(position);
        holder.iv_step.setOnClickListener(this);
        holder.o_tv_select.setOnClickListener(this);
        holder.iv_delete.setOnClickListener(this);
        holder.iv_add.setOnClickListener(this);
        holder.iv_minus.setOnClickListener(this);
        Operator operator = items.get(position);
        holder.et_time.setText(Integer.toString(operator.getDelayTime()));
        holder.o_tv_num.setText(Integer.toString(operator.getNum()));
        holder.o_tv_select.setText(getNameConcat(operator));
        holder.et_time.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                resetOperatorTime(s.toString(), position);
            }
        });
        return convertView;
    }


    private String getNameConcat(Operator operator) {
        String temp = operator.getName();
        switch (operator.getName()) {
            case Constant.ACTION_NAME_JSC:
                temp = operator.getName() + "_" + operator.getValue();
                break;
            case Constant.ACTION_NAME_KQJR:
                temp = operator.getName() + "_" + operator.getValue() + "档" + operator.getValue1() + "℃";
                break;
            case Constant.ACTION_NAME_FW:
                if (operator.getValue() == 0) {
                    temp = operator.getName() + "_" + Constant.ACTION_NAME_JSC;
                } else {
                    temp = operator.getName() + "_" + "锅体";
                }
                break;
            case Constant.ACTION_NAME_KSJB:
                temp = operator.getName() + "_" + changeValue(operator.getValue1()) + "_" + changeDirValue(operator.getValue());
                break;
            case Constant.ACTION_NAME_T:
            case Constant.ACTION_NAME_Y:
            case Constant.ACTION_NAME_JJ:
                temp = operator.getName() + "_" + operator.getValue1() + "克";
                break;
            case Constant.ACTION_NAME_JGG:
                temp = operator.getName() + "_" + (operator.getValue() == 1 ? "加盖" : "开盖");
                break;
            case Constant.ACTION_NAME_LAOCHOU:
            case Constant.ACTION_NAME_HHJY:
            case Constant.ACTION_NAME_HONGYOU:
            case Constant.ACTION_NAME_YOU:
            case Constant.ACTION_NAME_GQZ:
            case Constant.ACTION_NAME_YTJJ:
            case Constant.ACTION_NAME_SHUI:
            case Constant.ACTION_NAME_SHUI1:
            case Constant.ACTION_NAME_JLA:
                temp = operator.getName() + "_" + operator.getValue1() + "毫升";
                break;
            case Constant.ACTION_NAME_CCJD:
                int temp1 = operator.getValue1();
                temp = operator.getName() + "_" + temp1 + "档斜度";
                break;
            case Constant.ACTION_NAME_CCSC:
                int xs = operator.getValue1();
                if (xs <= 0 || xs > 100) {
                    xs = 100;
                }
                Log.e(TAG, "name:xs=" + xs);
                temp = operator.getName() + "_" + xs + "%";
                break;
        }

        return temp;
    }

    private String changeDirValue(int level) {
        if (level == 1) {
            return "反";
        }
        return "正";
    }

    private String changeValue(int level) {
        if (level == 1) {
            return "慢-";
        }
        if (level == 2) {
            return "慢";
        }
        if (level == 3) {
            return "慢+";
        }
        if (level == 4) {
            return "中-";
        }
        if (level == 5) {
            return "中";
        }
        if (level == 6) {
            return "中+";
        }
        if (level == 7) {
            return "快-";
        }
        if (level == 8) {
            return "快";
        }
        if (level == 9) {
            return "快+";
        }
        return "";
    }


    private void resetOperatorTime(String time, int position) {
        if (TextUtils.isEmpty(time)) {
            time = "0";
        }
        Operator operator = items.get(position);
        operator.setDelayTime(Integer.parseInt(time));
        items.remove(position);
        items.add(position, operator);
//        Log.e(TAG,"time="+items.get(position).getDelayTime());
    }


    @Override
    public void onClick(View v) {
        try {
            handlerClick(v);
        } catch (Exception e) {
            Log.e(TAG, "异常信息:" + e.getMessage());
        }
    }

    private void handlerClick(View v) {
        index = (int) v.getTag();
        switch (v.getId()) {
            case R.id.o_iv_delete:
                deleteData(v);
                break;
            case R.id.o_iv_step:
                addData(v);
                break;
            case R.id.o_iv_add:
                edEt(v, 1);
                break;
            case R.id.o_iv_minus:
                edEt(v, -1);
                break;
            case R.id.o_tv_operator:
                if (enableDelete) {
                    showMsg("该模式下不能对操作进行更改");
                    return;
                }
                Intent intent = new Intent(activity, SelectperatorActivity.class);
                intent.putExtra("src", src);
                activity.startActivityForResult(intent, 1024);
                break;
        }
    }


    private void addData(View et) {
        try {
            if (enableDelete) {
                showMsg("该模式下不能对操作进行删减");
                return;
            }
            int position = (Integer) et.getTag();
            Operator operator = new Operator();
            operator.setNum(position + 1);
            items.add(operator.getNum(), operator);
            for (int i = position + 1; i < items.size(); i++) {
                Operator o = items.get(i);
                items.remove(i);
                o.setNum(o.getNum() + 1);
                items.add(i, o);
            }
            notifyDataSetChanged();
        } catch (Exception e) {

        }
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        Collections.sort(items);
    }

    private void deleteData(View et) {
        try {
            if (enableDelete) {
                showMsg("该模式下不能对操作进行删除");
                return;
            }
            if (items.size() <= 1) {
                showMsg("不能全部删除");
                return;
            }
            int position = (Integer) et.getTag();
            deleteItem(items.get(position));
            notifyDataSetChanged();
        } catch (Exception e) {

        }
    }

    /**
     * 删除已存在的操作步骤
     *
     * @param operator
     */
    private void deleteItem(Operator operator) {
        try {
            operatorDao.delete(operator);
            items.remove(operator);
            Collections.sort(items);
            for (int i = 0; i < items.size(); i++) {
                Operator temp = items.get(i);
                items.remove(temp);
                temp.setNum(i + 1);
                items.add(i, temp);
            }
        } catch (Exception e) {

        }
    }


    private void edEt(View et, int value) {
        try {
            int position = (Integer) et.getTag();
            Operator operator = items.get(position);
            int time = operator.getDelayTime() + value;
            if (time > 255) {
                showMsg("时长不能超过255");
                return;
            }
            if (time < 0) {
                time = 0;
            }
            operator.setDelayTime(time);
            items.remove(position);
            items.add(position, operator);
            notifyDataSetChanged();
        } catch (Exception e) {

        }
    }


    public void setIndex(int position) {
        index = position;
    }


    static class ViewHolder {
        TextView o_tv_num, o_tv_select;
        EditText et_time;
        ImageView iv_delete, iv_add, iv_minus, iv_step;
    }

    private void showMsg(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
}